package com.jhhc.utils;


import sun.misc.BASE64Encoder;

import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;

public class ImageBase64 {
    private final static String ENCODE = "GBK";

    //图片转为Base64字符串
    public String convertFileToBase64(String imgPath) throws IOException {

        byte[] data = null;
        // 读取图片字节数组
        InputStream InputStream = new FileInputStream(imgPath);
        data = new byte[InputStream.available()];
        InputStream.read(data);
        InputStream.close();
        // 对字节数组进行Base64编码，得到Base64编码的字符串
        BASE64Encoder BASE64Encoder = new BASE64Encoder();
        String base64Str = BASE64Encoder.encode(data);
        return base64Str;
    }

    //转码
    public String getURLEncoderString(String str) throws UnsupportedEncodingException {
        String result = "";
        if (str == null){
            return "";
        }
        result = java.net.URLEncoder.encode(str,ENCODE);
        return result;
    }

    //解码
    public String getURLDecoderString(String str) throws UnsupportedEncodingException {
        String result = "";
        if (str == null){
            return "";
        }
        result = java.net.URLDecoder.decode(str,ENCODE);
        return result;
    }

    public void Base64ToconvertFile(String str,String path) throws IOException {
        FileOutputStream outputStream = null;
        try {
            Base64.Decoder decoder = Base64.getMimeDecoder();
            byte[] bytes = decoder.decode(str);
            outputStream = new FileOutputStream(path);
            outputStream.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }

    //date转字符串
    public String DateToStr(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = format.format(date);
        return str;
    }
    //保留2位小数
    public String doubleAccuracy2(double point){
        return String.format("%.2f", point);
    }
    //计算库容
    public double W(double x1,double y1,double x2,double y2,double x){
        double a = (y2-y1)/(x2-x1);
        double b = y1 - x1 * a;
        double w = a * x + b;
        w =Double.parseDouble(String.format("%.3f",w));
        BigDecimal decimal = new BigDecimal(w);
        return decimal.setScale(3,BigDecimal.ROUND_HALF_UP).doubleValue();
    }
    //计算水位
    public double RZ(double x1,double y1,double x2,double y2,double y){
        double a = (y2-y1)/(x2-x1);
        double b = y1 - x1 * a;
        double rz = (b-y)/a;
        double rz1 = Math.abs(rz);
        BigDecimal decimal = new BigDecimal(rz1);
        return decimal.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
    }

}
